package com.example.scandemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.hardware.ScanDevice;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;

public class MainActivity extends AppCompatActivity {

    private ScanDevice mScanDevice;
    private MediaPlayer mmediaplayer;
    private MediaPlayer paySuccessMmediaplayer;
    private MediaPlayer payFailMmediaplayer;
    private EditText showScanResult;
    private EditText mtime;
    private Button loginBtn;
    private Button logoutBtn;
    private EditText accountEditText;
    private EditText passwordEditText;
    private View loginLayout;
    private View logoutLayout;
    private TextView jfTextView;
    private TextView shopNameTextView;

    private TextView resultTextView;

    private final String serverURL= "https://jiash.huntkey.com/api/jialife/"; //"https://ht.rhzsz.com/api2/jialife/";

    private BroadcastReceiver mScanDataReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action!=null && action.equals("ACTION_BAR_SCAN")) {
                String str = intent.getStringExtra("EXTRA_SCAN_DATA");
                if(str != null){
                    mmediaplayer.start();

//                showScanResult.append(str + "\n");
                    if (showScanResult.getText().toString().isEmpty()){
                        Toasty.warning(MainActivity.this, "请输入积分", Toast.LENGTH_SHORT, true).show();
                        return;
                    }
                    if (!str.contains(String.valueOf("userId"))){
                        Toasty.warning(MainActivity.this, "请扫正确的付款码", Toast.LENGTH_SHORT, true).show();
                        return;
                    }
                    String test = showScanResult.getText().toString();
                    showScanResult.setText(test);
                    showScanResult.setSelection(showScanResult.getText().length());
                    try {
                        JSONObject jsonObject = new JSONObject(str);
                        System.out.println(jsonObject);
                        deductPaymentRequest(jsonObject);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScanDevice = new ScanDevice(this);  //初始化接口  Initialization interface

        IntentFilter scanDataIntentFilter = new IntentFilter();
        scanDataIntentFilter.addAction("ACTION_BAR_SCAN");
        registerReceiver(mScanDataReceiver, scanDataIntentFilter);

        mmediaplayer = new MediaPlayer(); //   Initialize sound
        mmediaplayer = MediaPlayer.create(this, R.raw.scanok);
        mmediaplayer.setLooping(false);

        paySuccessMmediaplayer = new MediaPlayer(); //   Initialize sound
        paySuccessMmediaplayer = MediaPlayer.create(this, R.raw.pay_success);
        paySuccessMmediaplayer.setLooping(false);

        payFailMmediaplayer = new MediaPlayer(); //   Initialize sound
        payFailMmediaplayer = MediaPlayer.create(this, R.raw.pay_fail);
        payFailMmediaplayer.setLooping(false);

        showScanResult = (EditText) findViewById(R.id.editText1);
        // 设置不弹出软键盘（API 21 及以上）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            showScanResult.setShowSoftInputOnFocus(false);
        }

// 仍然允许物理键盘输入
        showScanResult.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

// 保持焦点和光标可见
        showScanResult.setFocusable(true);
        showScanResult.setFocusableInTouchMode(true);
        showScanResult.setCursorVisible(true);
        showScanResult.requestFocus();

//        mtime = (EditText) findViewById(R.id.time);
        mScanDevice.openScan();  //Power on
        accountEditText = findViewById(R.id.accountEditTextId);
        passwordEditText = findViewById(R.id.passwordEditTextId);
        loginLayout = findViewById(R.id.loginLayoutId);
        logoutLayout = findViewById(R.id.logoutLayoutId);
        logoutBtn = findViewById(R.id.logoutBtnId);
        jfTextView = findViewById(R.id.jfTextViewId);
        shopNameTextView = findViewById(R.id.shopNameTextViewId);
        resultTextView = findViewById(R.id.resultTextViewId);
        loginBtn = (Button) findViewById(R.id.forceUpgrade);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    loginHandle();
                } catch (JSONException e) {
                    Toasty.warning(MainActivity.this, e.toString(), Toast.LENGTH_SHORT, true).show();
                }
            }
        });
        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPref = getSharedPreferences("my_data", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.clear();
                editor.apply();
                setMineInfoHandle();
            }
        });
        jfTextView.setText("0");
        setMineInfoHandle();
    }

    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.openScanner:
//                mScanDevice.openScan();  //Power on
//                break;
//            case R.id.closeScanner:
//                mScanDevice.closeScan(); // Power off
//                break;
//            case R.id.startDecode:
//                mScanDevice.startScan(); // star scan
//                break;
//            case R.id.stopDecode:
//                mScanDevice.stopScan(); // stop scan
//                break;
//            case R.id.start_continue:
//                mScanDevice.ContinousStart();  //open continued scanner
//                break;
//            case R.id.stop_continue:
//                mScanDevice.ContinousStop();//close  continued scanner
//                break;
//            case R.id.close:
//                finish();
//                break;
//            case R.id.ceanl:
//                showScanResult.setText("");
//                break;
//            case R.id.scan_time:
////                int time = Integer.parseInt(mtime.getText().toString());
////                if(time > 30) {
////
////                    mScanDevice.TimeScan(time);
////                }
//
//            default:
//                break;
//        }
    }

    //  Monitor Scan Key
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_NUMPAD_ENTER:
            case KeyEvent.KEYCODE_F4:
            case KeyEvent.KEYCODE_F7:
            case KeyEvent.KEYCODE_F1:
            case KeyEvent.KEYCODE_F2:
            case KeyEvent.KEYCODE_F8:
                // scanning
                if (event.getRepeatCount() == 0) {
                    mScanDevice.startScan();
                }
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();

        if (mScanDevice != null) {
            mScanDevice.closeScan();
            mScanDevice = null;
            unregisterReceiver(mScanDataReceiver);
        }
        if(mmediaplayer != null){
            mmediaplayer.release();
            mmediaplayer = null;
        }
        if(paySuccessMmediaplayer != null){
            paySuccessMmediaplayer.release();
            paySuccessMmediaplayer = null;
        }
        if(payFailMmediaplayer != null){
            payFailMmediaplayer.release();
            payFailMmediaplayer = null;
        }
    }

    public void loginHandle() throws JSONException {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = serverURL+"auth/loginShop";
        String account = accountEditText.getText().toString();
        String psd = passwordEditText.getText().toString();
        if (account.isEmpty()){
            Toasty.warning(MainActivity.this, "账号不能为空", Toast.LENGTH_SHORT, true).show();
            return;
        }
        if (psd.isEmpty()){
            Toasty.warning(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT, true).show();
            return;
        }
        loginBtn.setText("登录中...");
        JSONObject jsonObject = new JSONObject();
        String ras = RSAUtil.getRsaStr(psd);

        jsonObject.put("password",ras);
        jsonObject.put("username",account);//"13986465480"
        System.out.println(jsonObject);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // 成功回调
                        loginBtn.setText("登录");
                        System.out.println(response);
                        try {
                            if (response.getInt("code") != 200){
                                Toasty.error(MainActivity.this, response.getString("message"), Toast.LENGTH_SHORT, true).show();
                                return;
                            }
                            JSONObject jsonObject1 = response.getJSONObject("data");
                            System.out.println(jsonObject1);
                            JSONObject user = jsonObject1.getJSONObject("user");
                            // 保存数据
                            SharedPreferences sharedPref = getSharedPreferences("my_data", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
                            editor.putString("token", jsonObject1.getString("token"));
                            editor.putString("shopId", user.getString("shopId"));
                            editor.putString("name", user.getString("name"));
                            editor.putString("phone", user.getString("phone"));
                            editor.putString("shopName",user.getString("realName"));
                            editor.apply();
                            Toasty.success(MainActivity.this, "登录成功", Toast.LENGTH_SHORT, true).show();

                            setMineInfoHandle();
                        } catch (JSONException e) {
                            loginBtn.setText("登录");
                            Toasty.error(MainActivity.this, e.toString(), Toast.LENGTH_SHORT, true).show();
//                            throw new RuntimeException(e);
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 错误处理
                        loginBtn.setText("登录");
//                        System.out.println(error);
                        Toasty.error(MainActivity.this, error.toString(), Toast.LENGTH_SHORT, true).show();
                    }
                });

        queue.add(request);
    }

    private void setMineInfoHandle(){
        jfTextView.setText("0");
        SharedPreferences sharedPref = getSharedPreferences("my_data", Context.MODE_PRIVATE);
        final String token = sharedPref.getString("token", "");
        final String shopName = sharedPref.getString("shopName","");
        try {
            if (token==null || token.isEmpty()){
                logoutLayout.setVisibility(View.GONE);
                loginLayout.setVisibility(View.VISIBLE);
            }else {
                loginLayout.setVisibility(View.GONE);
                logoutLayout.setVisibility(View.VISIBLE);
                shopNameTextView.setText(shopName);
                shopStorePointsRequest();
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void deductPaymentRequest(JSONObject params){ //提交
        resultTextView.setVisibility(View.VISIBLE);
        resultTextView.setText("扫码状态：扫码中...");
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = serverURL+"mealCompensationPoints/deductPayment";
        JSONObject jsonObject = new JSONObject();
        // 读取数据
        SharedPreferences sharedPref = getSharedPreferences("my_data", Context.MODE_PRIVATE);
        final String token = sharedPref.getString("token", "");
        String shopId = sharedPref.getString("shopId", "");
        try {
            jsonObject.put("shopId",shopId);
            jsonObject.put("ruleSettings",showScanResult.getText());
            jsonObject.put("userId",params.getString("userId"));
            jsonObject.put("goodId",params.getString("goodId"));
            System.out.println(jsonObject);
        } catch (Exception e) {
            Log.d("vendor.scn.test", "scannerStatusChange: 重新连接失败");
        }


        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // 成功回调
                        System.out.println(response);
//                        resultTextView.setVisibility(View.GONE);
                        resultTextView.setText("扫码状态：待扫码");
                        try {
                            if (response.getInt("code") == 200){
                                paySuccessMmediaplayer.start();
                                Toasty.success(MainActivity.this, "支付成功", Toast.LENGTH_SHORT, true).show();
                                showScanResult.setText("");
                                // 隐藏软键盘
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(showScanResult.getWindowToken(), 0);
                                // 保持焦点
                                showScanResult.requestFocus();
                                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        shopStorePointsRequest();
                                    }
                                }, 1000); // 延迟时间，单位是毫秒（1秒 = 1000毫秒）
                                return;
                            }
                            showScanResult.setText("");
                            payFailMmediaplayer.start();
                            Toasty.error(MainActivity.this, response.getString("message"), Toast.LENGTH_SHORT, true).show();
                        } catch (JSONException e) {
                            showScanResult.setText("");
                            payFailMmediaplayer.start();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 错误处理
//                        resultTextView.setVisibility(View.GONE);
                        resultTextView.setText("扫码状态：待扫码");
                        showScanResult.setText("");
                        System.out.println(error);
                        Toasty.error(MainActivity.this, error.toString(), Toast.LENGTH_SHORT, true).show();
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
//                return super.getHeaders();
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Bearer " + token); // 添加 Token
                headers.put("Content-Type", "application/json");  // 设置 Content-Type
                headers.put("Accept", "application/json");         // 可选
                return headers;
            }
        };
        queue.add(request);
    }

    public void shopStorePointsRequest(){ //获取店铺积分
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = serverURL+"shop/shopStorePointsApp";
        // 读取数据
        SharedPreferences sharedPref = getSharedPreferences("my_data", Context.MODE_PRIVATE);
        final String token = sharedPref.getString("token", "");
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // 成功回调
                        System.out.println(response);
//                        resultTextView.setVisibility(View.GONE);
                        try {
                            if (response.getInt("code") == 200){
                                JSONObject jsonObject1 = response.getJSONObject("data");
                                if (jsonObject1!=null){
                                    final Long total = jsonObject1.getLong("total");
                                    if (jfTextView != null)
                                        jfTextView.setText(total.toString());
                                }
                                return;
                            }
                            Toasty.error(MainActivity.this, response.getString("message"), Toast.LENGTH_SHORT, true).show();
                        } catch (JSONException e) {
                            System.out.println(e);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toasty.error(MainActivity.this, error.toString(), Toast.LENGTH_SHORT, true).show();
                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
//                return super.getHeaders();
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Bearer " + token); // 添加 Token
                headers.put("Content-Type", "application/json");  // 设置 Content-Type
                headers.put("Accept", "application/json");         // 可选
                return headers;
            }
        };
        queue.add(request);
    }

}